<template>
  <div class="system-config-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">
            <el-icon><Setting /></el-icon>
            系统配置
          </span>
          <el-button 
            v-permission="'config.edit'" 
            type="primary" 
            :icon="Plus" 
            @click="handleAdd"
          >
            添加配置
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchForm.search"
          placeholder="搜索配置键、描述"
          style="width: 300px"
          clearable
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select
          v-model="searchForm.config_type"
          placeholder="配置类型"
          clearable
          style="width: 150px; margin-left: 10px"
          @change="handleSearch"
        >
          <el-option 
            v-for="type in configTypes" 
            :key="type.value" 
            :label="type.label" 
            :value="type.value" 
          />
        </el-select>

        <el-button type="primary" :icon="Search" @click="handleSearch" style="margin-left: 10px">
          搜索
        </el-button>
        <el-button :icon="RefreshRight" @click="handleReset">重置</el-button>
      </div>

      <!-- 配置列表 -->
      <el-table 
        :data="configList" 
        v-loading="loading"
        border
        stripe
        style="margin-top: 20px"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="key" label="配置键" min-width="180" />
        <el-table-column label="配置类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getConfigTypeTag(row.config_type)">
              {{ getConfigTypeLabel(row.config_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="value" label="配置值" min-width="200">
          <template #default="{ row }">
            <div class="config-value">
              {{ row.value.length > 50 ? row.value.substring(0, 50) + '...' : row.value }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="180" />
        <el-table-column label="是否公开" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_public ? 'success' : 'info'">
              {{ row.is_public ? '公开' : '私有' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" min-width="160">
          <template #default="{ row }">
            {{ formatDate(row.updated_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-permission="'config.edit'" 
              link 
              type="primary" 
              size="small" 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              v-permission="'config.edit'" 
              link 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; justify-content: flex-end"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- 添加/编辑配置对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="configFormRef"
        :model="configForm"
        :rules="configRules"
        label-width="100px"
      >
        <el-form-item label="配置键" prop="key">
          <el-input v-model="configForm.key" :disabled="isEdit" placeholder="请输入配置键（英文）" />
        </el-form-item>
        <el-form-item label="配置类型" prop="config_type">
          <el-select v-model="configForm.config_type" placeholder="请选择配置类型" style="width: 100%">
            <el-option 
              v-for="type in configTypes" 
              :key="type.value" 
              :label="type.label" 
              :value="type.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="配置值" prop="value">
          <el-input 
            v-model="configForm.value" 
            type="textarea"
            :rows="4"
            placeholder="请输入配置值" 
          />
        </el-form-item>
        <el-form-item label="配置描述" prop="description">
          <el-input v-model="configForm.description" placeholder="请输入配置描述" />
        </el-form-item>
        <el-form-item label="是否公开">
          <el-switch v-model="configForm.is_public" />
          <span style="margin-left: 10px; color: #999; font-size: 12px">
            公开配置可以被前端直接访问
          </span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Setting, Plus, Search, RefreshRight } from '@element-plus/icons-vue'
import { getConfigList, getConfigTypes, createConfig, updateConfig, deleteConfig } from '@/api/system'

// 配置类型
const configTypes = ref([])

// 搜索表单
const searchForm = reactive({
  search: '',
  config_type: ''
})

// 配置列表
const configList = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('添加配置')
const isEdit = ref(false)
const submitting = ref(false)
const configFormRef = ref(null)

// 配置表单
const configForm = reactive({
  id: null,
  key: '',
  value: '',
  config_type: 'other',
  description: '',
  is_public: false
})

// 表单验证规则
const configRules = {
  key: [{ required: true, message: '请输入配置键', trigger: 'blur' }],
  config_type: [{ required: true, message: '请选择配置类型', trigger: 'change' }],
  value: [{ required: true, message: '请输入配置值', trigger: 'blur' }],
  description: [{ required: true, message: '请输入配置描述', trigger: 'blur' }]
}

// 获取配置类型标签颜色
const getConfigTypeTag = (type) => {
  const tagMap = {
    'system': 'primary',
    'email': 'success',
    'storage': 'warning',
    'security': 'danger',
    'other': 'info'
  }
  return tagMap[type] || 'info'
}

// 获取配置类型标签
const getConfigTypeLabel = (type) => {
  const typeObj = configTypes.value.find(t => t.value === type)
  return typeObj ? typeObj.label : type
}

// 获取配置类型列表
const fetchConfigTypes = async () => {
  try {
    const response = await getConfigTypes()
    configTypes.value = response
  } catch (error) {
    console.error('获取配置类型失败:', error)
    // 使用默认类型
    configTypes.value = [
      { value: 'system', label: '系统配置' },
      { value: 'email', label: '邮件配置' },
      { value: 'storage', label: '存储配置' },
      { value: 'security', label: '安全配置' },
      { value: 'other', label: '其他配置' }
    ]
  }
}

// 获取配置列表
const fetchConfigList = async () => {
  loading.value = true
  try {
    // 过滤掉空参数
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize
    }
    
    // 只添加非空的搜索参数
    if (searchForm.search) params.search = searchForm.search
    if (searchForm.config_type) params.config_type = searchForm.config_type
    if (searchForm.is_public) params.is_public = searchForm.is_public
    
    const response = await getConfigList(params)
    configList.value = response.results || response
    pagination.total = response.count || 0
  } catch (error) {
    ElMessage.error('获取配置列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchConfigList()
}

// 重置
const handleReset = () => {
  searchForm.search = ''
  searchForm.config_type = ''
  handleSearch()
}

// 添加配置
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '添加配置'
  Object.assign(configForm, {
    id: null,
    key: '',
    value: '',
    config_type: 'other',
    description: '',
    is_public: false
  })
  dialogVisible.value = true
}

// 编辑配置
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑配置'
  Object.assign(configForm, {
    id: row.id,
    key: row.key,
    value: row.value,
    config_type: row.config_type,
    description: row.description,
    is_public: row.is_public
  })
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!configFormRef.value) return
  
  await configFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    try {
      if (isEdit.value) {
        await updateConfig(configForm.id, configForm)
        ElMessage.success('更新配置成功')
      } else {
        await createConfig(configForm)
        ElMessage.success('添加配置成功')
      }
      dialogVisible.value = false
      fetchConfigList()
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '操作失败')
      console.error(error)
    } finally {
      submitting.value = false
    }
  })
}

// 删除配置
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除配置 ${row.key} 吗？`,
      '警告',
      { type: 'error' }
    )
    
    await deleteConfig(row.id)
    ElMessage.success('删除成功')
    fetchConfigList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 对话框关闭
const handleDialogClose = () => {
  if (configFormRef.value) {
    configFormRef.value.resetFields()
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 挂载时获取数据
onMounted(() => {
  fetchConfigTypes()
  fetchConfigList()
})
</script>

<style scoped>
.system-config-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header .title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
}

.search-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px 0;
}

.config-value {
  word-break: break-all;
}
</style>

